﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Web;
using System.Net;
using System.Management;
using System.Net.Sockets;

namespace comm
{
    public partial class Form1 : Form
    {
        BLL.tbl_Detect bl = new BLL.tbl_Detect();
        BLL.tbl_Sensor bsen = new BLL.tbl_Sensor();
        MODEL.tbl_Detect mbl = new MODEL.tbl_Detect();
        BLL.tbl_AlarmNorm blalarm = new BLL.tbl_AlarmNorm();
        BLL.tbl_Excessive blex = new BLL.tbl_Excessive();
        MODEL.tbl_Excessive mlex = new MODEL.tbl_Excessive();

        
        //private Thread theead;
        private string dz; string kkk; string temperature; string shidu; string address; int zt; string zhuangtai; DataTable mysj;

        // Queue<byte> strList = new Queue<byte>();
        System.Timers.Timer t11 = new System.Timers.Timer();


        public Form1()
        {
            InitializeComponent();
            comboxbind();
            mysj = bsen.GetList(" status=0 ").Tables[0];
            this.textBox3.Text = (mysj.Rows.Count*1000).ToString();
        }
        class CListItem  //Combox下拉框手动赋值类
        {
            private string _disText;
            private string _disValue;
            public CListItem()
            {
            }

            public CListItem(string disText, string disValue)
            {
                _disText = disText;
                _disValue = disValue;
            }
            public string DisText
            {
                get { return _disText; }
                set { _disText = value; }
            }
            public string DisValue
            {
                get { return _disValue; }
                set { _disValue = value; }
            }
        }

        protected void getcomname() //遍历本机com口
        {
            //string[] portNames = SerialPort.GetPortNames();
            //for (int i = 0; i < portNames.Length - 1; i++)
            //{
            //    this.comboBox1.Items.Add(portNames[i]);
            //    comboBox1.SelectedIndex = 0;
            //}
            //this.comboBox1.Items.Add(this.serialPort1.PortName);


            string[] Port = axSzhtoSms1.YhGetComPort().Split(',');
            for (int i = 0; i < Port.Length; i++)
                comboBox1.Items.Add(Port[i]);
            comboBox1.Text = Port[0];







        }

        protected void comboxbind()
        {
            List<CListItem> list1 = new List<CListItem>();
            list1.Add(new CListItem("1200", "1200"));
            list1.Add(new CListItem("2400", "2400"));
            list1.Add(new CListItem("4800", "4800"));
            list1.Add(new CListItem("9600", "9600"));
            list1.Add(new CListItem("14400", "14400"));
            list1.Add(new CListItem("19200", "19200"));
            list1.Add(new CListItem("38400", "38400"));
            comboBox2.DataSource = list1;
            comboBox2.DisplayMember = "DisText";
            comboBox2.ValueMember = "DisValue";
            comboBox2.SelectedValue = "2400";
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) //定时从数据库取地址数据
        {
            //StringToByte(serialPort1);//16进制发送
            GetAddress();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (getmac() == "6C:62:6D:87:8E:37" || getmac() == "B8:88:E3:3C:14:72" || getmac() == "E0:06:E6:C4:CB:F6" || getmac() == "30:85:A9:8F:92:36")
            {
                //if (System.DateTime.Now.Date < Convert.ToDateTime("2013-01-08"))
                //{

                    if (serialPort1.IsOpen == false)
                    {
                        serialPort1.PortName = "COM" + comboBox1.SelectedItem.ToString().Trim();
                        serialPort1.BaudRate = Convert.ToInt32(this.comboBox2.SelectedValue.ToString());
                        serialPort1.DataBits = 8;
                        serialPort1.StopBits = StopBits.One;
                        serialPort1.Open();
                    }
                    this.button1.Enabled = false;
                    this.button2.Enabled = true;
                    //serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
                    t11.Interval = Convert.ToDouble(this.textBox3.Text);
                    t11.Start();
                    t11.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
                    t11.AutoReset = true;
                    t11.Enabled = true;
                //}
                //else
                //{
                //    MessageBox.Show("软件已过期！！");
 
                //}

            }
            else
            {
                MessageBox.Show("请勿盗版！");
            }




        
            
            //theead = new Thread(new ThreadStart(DoWork));
        }

        protected void GetAddress()  //延时循环读取传感器地址表
        {
            try
            {
                //DataTable mysj = bsen.GetList(" status=0 ").Tables[0];
                //t11.Interval = Convert.ToDouble(mysj.Rows.Count);
                for (int i = 0; i < mysj.Rows.Count; i++)
                {
                    if (t11.Enabled == false)
                    {
                        break;
                    }
                    else
                    {
                        string adr = mysj.Rows[i]["SensorCode"].ToString().Trim();
                        dz = mysj.Rows[i]["SensorAddress"].ToString().Trim();
                        StringToByte(serialPort1, adr); //以16进制的方式发送
                        Thread.Sleep(Convert.ToInt32(this.textBox1.Text));
                    }
                }
            }
            catch
            {
                this.serialPort1.Close();
                this.t11.Enabled = false;
                t11.AutoReset = false;
                this.t11.Close();
                this.t11.Stop();
                //MessageBox.Show("没有网络连接！");
            }

        }
        #region 字符转为16进制byte并发送，接口为串口、传感器地址
        private void StringToByte(SerialPort serialPort, string address)
        {
            byte[] ByteOut;
            try
            {
                string[] ByteStrings = new string[address.Length / 2];
                int j = 0;
                for (int i = 0; i < ByteStrings.Length; i++)
                {
                    ByteStrings[i] = address.Substring(j, 2);
                    j += 2;
                }
                ByteOut = new byte[ByteStrings.Length];
                for (int i = 0; i <= ByteStrings.Length - 1; i++)
                {
                    ByteOut[i] = byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            string str = System.Text.Encoding.Default.GetString(ByteOut);
            serialPort.Write(ByteOut, 0, ByteOut.Length);
        }
        #endregion

        #region 关闭监测按钮事件
        private void button2_Click(object sender, EventArgs e)
        {
            this.button1.Enabled = true;
            this.button2.Enabled = false;
            //this.t11.Enabled = false;
            //t11.AutoReset = false;
            //this.t11.Close();
            this.t11.Stop();
            this.txtReceive.Clear();
            //this.serialPort1.Close();
            //this.serialPort1.Dispose();
            //this.t11.Dispose();
            //this.Close();
        }
        #endregion

        #region byte[] 转成原16进制格式的string
        public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF "
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = 0; i < bytes.Length; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        #endregion


        public void closemethed()
        {
            this.serialPort1.Close();
            this.t11.Enabled = false;
            t11.AutoReset = false;
            this.t11.Close();
            this.t11.Dispose();
        }


        #region 关闭窗口时触发的事件
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Verify v2 = new Verify();
            
            //v2.Show();
            
 
        }
        #endregion

        #region 委托在数据显示文本框进行的线程
        private void serialPort1_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(Convert.ToInt32(this.textBox2.Text));
            byte firstByte = Convert.ToByte(serialPort1.ReadByte());
            int bytesRead = serialPort1.BytesToRead;
            byte[] bytesData = new byte[bytesRead + 1];
            bytesData[0] = firstByte;
            for (int i = 1; i <= bytesRead; i++)
                bytesData[i] = Convert.ToByte(serialPort1.ReadByte());

            try
            {
                if (bytesData.Length < 9) //如果传感器故障或数据接收不全
                {
                    this.serialPort1.DiscardInBuffer();
                    //temperature = "";
                    //shidu = "";
                    //address = dz;
                    //zt = 2;
                    //mbl.SensorID = Convert.ToInt32(address);
                    //mbl.Temperature = temperature;
                    //mbl.Humidity = shidu;
                    //mbl.Status = zt;
                    //bl.Add(mbl);
                }
                else
                {
                    kkk = ToHexString(bytesData);
                    shidu = (Convert.ToDouble(Convert.ToInt32(kkk.Substring(6, 4), 16)) / 10).ToString(); //获得温度 68.5
                    temperature = (Convert.ToDouble(Convert.ToInt32(kkk.Substring(10, 4), 16))/10).ToString(); //获得湿度 21
                    address = Convert.ToInt32(kkk.Substring(0, 2), 16).ToString(); //获得地址


                    if (Convert.ToDouble(temperature) < 100 && Convert.ToDouble(temperature) > 1 && Convert.ToDouble(shidu) < 101 && Convert.ToDouble(shidu) > 10)   //如果温度和湿度数据在正常范围
                    {
                        //-----数据写入数据库
                        mbl.SensorID = Convert.ToInt32(address);
                        mbl.Temperature = temperature;
                        mbl.Humidity = shidu;
                        //---------

                        //-----以下判断是否达到报警设置
                        double szwd;
                        double szsd;
                        double sswd = Convert.ToDouble(temperature); //实时温度
                        double sssd = Convert.ToDouble(shidu); //实时湿度
                        DataTable errdata = blalarm.GetList("SensorAddress='" + address + "'").Tables[0];
                        if (errdata.Rows.Count < 1)
                        {
                            szwd = 40;
                            szsd = 100;
                        }
                        else
                        {
                            szwd = Convert.ToDouble(errdata.Rows[0]["TemperatureHigh"].ToString());//获取设置温度
                            szsd = Convert.ToDouble(errdata.Rows[0]["HumidityLow"].ToString());// 获取设置湿度
                        }

                        if (sswd > szwd || sssd < szsd)
                        {
                            zt = 1;
                            mbl.Status = zt;
                            bl.Add(mbl);

                            if (!blex.ExistsExcessive(address)) //判断报警表传感器数据是否重复
                            {
                                mlex.SensorID = address;
                                blex.Add(mlex);
                            }
                        }
                        else
                        {
                            zt = 0;
                            mbl.Status = zt;
                            bl.Add(mbl);
                        }
                    }
                }
                string addr = "";
                if (address.Length < 2)
                {
                    addr = "0" + address;
                }
                else
                {
                    addr = address;
                }

                switch (zt)
                {
                    case 0:
                        zhuangtai = "正常";
                        break;
                    case 1:
                        zhuangtai = "报警";
                        break;
                    case 2:
                        zhuangtai = "故障";
                        break;

                }

                string list1 = "状态: " + zhuangtai + "  |地址：" + addr + "  |温度：" + temperature + "  |湿度：" + shidu + "%" + "  | 时间：" + System.DateTime.Now + Environment.NewLine + Environment.NewLine;

                this.txtReceive.Invoke(new MethodInvoker(delegate()
                {
                    txtReceive.AppendText(list1);
                    txtReceive.ScrollToCaret();
                    if (txtReceive.Text.Length >6000)
                    {
                        txtReceive.Clear();
                    }
                }
            ));
            }
            catch
            { }
            this.serialPort1.DiscardInBuffer();
        }
        #endregion

        private void button3_Click(object sender, EventArgs e)
        {
            loginyanzheng();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.textBox4.ReadOnly = false;
            this.textBox5.ReadOnly = false;
            this.textBox1.ReadOnly = true;
            this.textBox2.ReadOnly = true;
            this.textBox3.ReadOnly = true;
            this.comboBox1.Enabled = false;
            this.comboBox2.Enabled = false;
            this.button3.Enabled = true;
            this.button4.Enabled = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            simsend sm = new simsend();
            sm.Show();
            getcomname();
        }


        public static string getmac() //获取本机的Mac地址
        {
            string s = ""; string macs = "";
            string hostInfo = Dns.GetHostName();
            //System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;

            System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            for (int i = 0; i < addressList.Length; i++)
            {
                s += addressList[i].ToString();
            }
            ManagementClass mc;
            mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (mo["IPEnabled"].ToString() == "True")
                    macs = mo["MacAddress"].ToString();
            }
            return macs;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //Verify v2 = new Verify();
            //v2.Show();
            //this.Hide();
            if (this.button3.Enabled == true)
            {
                MessageBox.Show("您必须处于登录状态才能退出！");
            }
            else
            {
                
                this.Close();
                this.Dispose();
            }
        }

        private void button5_Click(object sender, EventArgs e) //任务图标缩小到托盘后台运行
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
 
            }
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
            if (this.notifyIcon1.Visible == false)
            {
                this.notifyIcon1.Visible = true;
            }
        }

        //private void starport()//短信猫注册
        //{
        //    int port = 4;
        //    string str = "9600,N,8,1";
        //    string sN = "868995833293722";
        //    //textBox4
        //    //打开端口
        //    //label5.Text = "初始化端口";
        //    string ret = axSzhtoSms1.YhOpenModem(port, str, sN);//如果成功，返回短信中心号

        //    if (ret.IndexOf("-1") > 0)
        //    {
        //        MessageBox.Show("短信猫初始化失败！请检查短信猫是否接好或者是否端口错误");
        //        return;
        //    }
        //}




        private void notifyIcon1_Click(object sender, EventArgs e) //托盘图标clik事件
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;
                this.Activate();
                this.notifyIcon1.Visible = false;
                this.ShowInTaskbar = true;    
            }
            else
            {
                this.WindowState = FormWindowState.Minimized;
                if (this.notifyIcon1.Visible == false)
                {
                    this.notifyIcon1.Visible = true;
                }
                this.ShowInTaskbar = false;     
            }
        }


        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            
            simsend v3 = new simsend();
            v3.Show();
        }


        protected void loginyanzheng()
        {
            if (this.textBox4.Text == "rongsheng" && this.textBox5.Text == "yate2012")
            {
                this.textBox4.ReadOnly = true;
                this.textBox5.ReadOnly = true;
                this.textBox1.ReadOnly = false;
                this.textBox2.ReadOnly = false;
                this.textBox3.ReadOnly = false;
                this.textBox4.Text = "";
                this.textBox5.Text = "";
                this.comboBox1.Enabled = true;
                this.comboBox2.Enabled = true;
                //getcomname();
                this.button3.Enabled = false;
                this.button4.Enabled = true;
                MessageBox.Show("登陆成功！");
            }
            else
            {
                MessageBox.Show("账号或密码错误！");
            }
        }


        private void textBox5_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                loginyanzheng();
            }
        }

        private void cgqToolStripMenuItem_Click(object sender, EventArgs e)
        {
            datasql v4 = new datasql();
            v4.Show();
        }






    }
}
